import { EggLogger } from 'egg';
import { Inject, HTTPController, HTTPMethod, HTTPMethodEnum, Context, EggContext, Middleware } from '@eggjs/tegg';
import { responseFormatter } from 'app/middleware/responseFormatter';
import { EggAppConfig } from 'typings/app';
// import { toInt, removeUndefinedValues } from 'app/libs/utils';
import * as tedious from 'tedious';

@HTTPController({
  path: '/temp',
})
@Middleware(responseFormatter)
export class TempController {
  @Inject()
  logger: EggLogger;
  @Inject()
  config: EggAppConfig;

  @HTTPMethod({
    method: HTTPMethodEnum.GET,
    path: '/getTempList',
  })
  async getTempList(@Context() ctx: EggContext) {
    const config: tedious.ConnectionConfig = {
      server: '192.168.3.52', // MSSQL服务器地址
      authentication: {
        type: 'default',
        options: {
          userName: 'cncpro', // 数据库用户名
          password: 'cncpro', // 数据库密码
        },
      },
      options: {
        database: 'CNCPROCommon', // 要连接的数据库名称
      },
    };
    const connection = new tedious.Connection(config);

    connection.on('connect', (err: any) => {
      if (err) {
        console.error('连接失败:', err);
      } else {
        console.log('成功连接到SQL Server');

        // 准备并执行查询
        const request = new tedious.Request(
          'SELECT * FROM T_MES_ProEnvironmentAddr limit 0,1',
          (err, rowCount) => {
            if (err) {
              console.error('查询失败:', err);
            } else {
              console.log(`${rowCount} 行返回.`);
              // 注意：在TypeScript中处理结果可能需要更具体的类型处理
            }

            // 查询完毕后关闭连接
            connection.close();
          });

        // 监听每一行数据
        request.on('row', columns => {
          const rowObject: any = {};
          columns.forEach(column => {
            rowObject[column.metadata.colName] = column.value;
          });
          ctx.logger.info(rowObject);
          console.log(rowObject);
        });

        // 执行请求
        connection.execSql(request);
      }
    });

    connection.on('end', () => {
      console.log('连接已关闭');
    });
    // });
    // const [list, total] = await ctx.model.query(`select a.ID,a.Device,a.DeviceName,a.Address,a.Line,a.Handler,a.STemperature,a.SHumidity,a.SIllumination,a.SCleanliness,a.Factory,a.FactoryName,a.DDLink,b.Abnormal,b.LastTime,a.AddPerson,a.AddTime,a.UpdatePerson,a.UpdateTime
    // from T_MES_ProEnvironmentAddr a
    // left join (select MachineName,Abnormal=convert(bit,case when Temperature<Convert(decimal(18,1),substring(STemperature, 0, CHARINDEX('-', STemperature)))
    // or Temperature> Convert(decimal(18, 1), SUBSTRING(STemperature, CHARINDEX('-', STemperature) + 1, LEN(STemperature)))
    // or Humidness<Convert(decimal(18,1),substring(SHumidity, 0, CHARINDEX('-', SHumidity)))
    // or Temperature> Convert(decimal(18, 1), SUBSTRING(SHumidity, CHARINDEX('-', SHumidity) + 1, LEN(SHumidity))) then 1 else 0 end),
    // LastTime = PustTime
    // from T_THmachineData
    // where Id in (select Max(Id) from T_THmachineData group by MachineName)) b on a.Device = b.MachineName;`);
    // return { list, total };
  }
}
